package com.blog.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.blog.entity.AdminUser;
import com.blog.myUtils.DateTime;
import com.blog.myUtils.Security;
import com.blog.service.AdminUserService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mars123
 * @since 2019-07-02
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Override
    public boolean login(String usernmae, String password, HttpSession session) {
        AdminUser adminUser = new AdminUser();
        adminUser = adminUser.selectOne(new EntityWrapper().eq("name", usernmae));
        if (adminUser != null && adminUser.getPassword().equals(Security.md5Salt(password))) {
            session.setAttribute("isLogin", true);
            session.setAttribute("user", adminUser);
            return true;
        }
        return false;
    }

    @Override
    public Page<AdminUser> index(AdminUser param, Page<AdminUser> page) {
        AdminUser adminUser = new AdminUser();
        return adminUser.selectPage(page, "1=1");
    }

    @Override
    public AdminUser create(AdminUser adminUser) {
        adminUser.setCreatedAt(DateTime.getTime());
        adminUser.setUpdatedAt(adminUser.getCreatedAt());
        if (adminUser.insert()) {
            return adminUser;
        } else {
            return null;
        }
    }

    @Override
    public AdminUser update(AdminUser adminUser) {
        if (adminUser.getPassword() != null) {
            adminUser.setPassword(Security.md5Salt(adminUser.getPassword()));
        }
        adminUser.setUpdatedAt(DateTime.getTime());
        if (adminUser.updateById()) {
            return adminUser;
        }
        return null;
    }

    @Override
    public boolean delete(int id) {
        AdminUser adminUser = new AdminUser();
        return adminUser.deleteById(id);
    }

    @Override
    public AdminUser view(int id) {
        return new AdminUser().selectById(id);
    }

}
